#define _CRT_SECURE_NO_WARNINGS 1
#include "LTNode.h"

LTNode* Malloc(DataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	return newnode;
}

LTNode* Init()
{
	LTNode* newnode = Malloc(0);

	newnode->next = newnode;
	newnode->prev = newnode;

	return newnode;
}

void LTPrintf(LTNode* phead)
{
	assert(phead);

	printf("phead<=>");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	putchar('\n');
}

void LTPushBack(LTNode* phead, DataType x)
{
	assert(phead);

	LTNode *newnode = Malloc(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;

	newnode->next = phead;
	phead->prev = newnode;

}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* tail = phead->prev;
	LTNode* newtail = tail->prev;

	newtail->next = phead;
	phead->prev = newtail;
	free(tail);
}

void LTPushFront(LTNode* phead, DataType x)
{
	assert(phead);

	LTNode* newnode = Malloc(x);
	LTNode* old_next = phead->next;

	phead->next = newnode;
	newnode->prev = phead;

	newnode->next = old_next;
	old_next->prev = newnode;

}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* del = phead->next;

	phead->next = del->next;
	del->next->prev = phead;

	free(del);
}

LTNode* LTFind(LTNode* phead, DataType x)
{
	assert(phead);
	
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}

	printf("nothing!\n");
	return NULL;
}

void LTInsert(LTNode* pos, DataType x)
{
	assert(pos);

	LTNode* newnode = Malloc(x);
	LTNode* posprev = pos->prev;

	posprev->next = newnode;
	newnode->prev = posprev;

	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* posprev = pos->prev;
	LTNode* posnext = pos->next;

	posprev->next = posnext;
	posnext->prev = posprev;
	free(pos);
}

void LTDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(cur);
}